<script setup lang="ts" name="DictData">
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { downloadBlobFile } from '@/utils'
import DataEditDialog from './components/DataEditDialog.vue'
import { listData, dataExport, delData } from '@/api/system/dictData/index'
import { getType, optionselect } from '@/api/system/dictType/index'
import { useTagsViewStore } from '@/store/tagsView'
import { warnBox } from '@/utils/utils'
import DictTag from '@/components/Dict/DictTag.vue'
import type { DictDataItem, QueryParams } from '@/api/system/dictData/type'
import { debounce } from 'es-toolkit'
import { formatDate } from '@/utils/day'

const router = useRouter()
const route = useRoute()
const tagsStore = useTagsViewStore()

const routeDictId = route.params.dictId as string
const defaultDictType = ref('')

const formValue = ref<QueryParams>({
	dictType: '',
	dictLabel: '',
	status: ''
})

const sysNormalDisable = ref<IGetDictsRes>([])
const typeOptions = ref<{ label: string; value: string }[]>([])

const formOptions = ref<FormItemRows[]>([
	{
		type: 'select',
		label: '字典名称',
		prop: 'dictType',
		options: typeOptions as unknown as any,
		attrs: {
			placeholder: '请选择字典名称',
			clearable: false,
			style: {
				width: '200px'
			}
		}
	},
	{
		type: 'input',
		label: '字典标签',
		prop: 'dictLabel',
		attrs: {
			placeholder: '请输入字典标签',
			clearable: true
		}
	},
	{
		type: 'select',
		label: '字典状态',
		prop: 'status',
		options: sysNormalDisable as unknown as any,
		attrs: {
			placeholder: '请选择字典状态',
			clearable: true,
			style: {
				width: '200px'
			}
		}
	}
])

// 表格数据
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<DictDataItem[]>([])
const columns = ref<TableColums[]>([
	{
		label: '字典编码',
		prop: 'id'
	},
	{
		label: '字典标签',
		prop: 'dictLabel'
	},
	{
		label: '字典键值',
		prop: 'dictValue'
	},
	{
		label: '字典排序',
		prop: 'dictSort'
	},
	{
		label: '状态',
		prop: 'status'
	},
	{
		label: '备注',
		prop: 'remark'
	},
	{
		label: '创建时间',
		prop: 'createTime'
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 160,
		align: 'center'
	}
])

// 对话框
const editDialogRef = useTemplateRef('editDialogRef')

const getTableData = async () => {
	loading.value = true
	try {
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value
		}
		const res = await listData(params)
		tableData.value = res.data.rows || []
		page.value.total = res.data.total || 0
	} catch (error) {
		console.error('获取字典数据列表失败:', error)
		tableData.value = []
		page.value.total = 0
	} finally {
		loading.value = false
	}
}

const handleAdd = () => {
	editDialogRef.value?.init('add', undefined, undefined, formValue.value.dictType)
}

const handleEdit = (row: DictDataItem) => {
	editDialogRef.value?.init('edit', row.id, undefined, formValue.value.dictType)
}

const handleDelete = async (rowId: string) => {
	await warnBox()
	await delData(rowId)
	ElMessage.success('删除成功')
	getTableData()
}

const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})

const exportFn = () => {
	const params = {
		...formValue.value,
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize
	}

	dataExport(params).then(data => {
		downloadBlobFile(data.data, data.filename ? data.filename : `dict_data_${new Date().getTime()}.xlsx`)
	})
}

const handleClose = () => {
	tagsStore.delView({
		path: route.path,
		name: route.name as string
	})
	router.replace('/system/dict')
}

function init() {
	getDicts('sys_normal_disable').then(data => {
		sysNormalDisable.value = data
	})

	/** 查询字典类型详细 */
	getType(routeDictId).then(response => {
		formValue.value.dictType = response.data.dictType
		defaultDictType.value = response.data.dictType
		getTableData()
	})

	/** 查询字典类型列表 */
	optionselect().then(response => {
		typeOptions.value = response.data.map(v => ({
			label: v.dictName,
			value: v.dictType
		}))
	})
}

onMounted(() => {
	init()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="
					() => {
						formValue.dictType = defaultDictType
						getTableData()
					}
				"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['system:dict:add'])"
						type="primary"
						@click="handleAdd"
					>
						新增
					</el-button>
					<el-button
						v-if="checkPermission(['system:dict:export'])"
						@click="handleExport"
					>
						导出
					</el-button>
					<el-button @click="handleClose"> 关闭 </el-button>
				</template>
				<template #dictLabel="{ row }">
					<span v-if="(row.listClass == '' || row.listClass == 'default') && (row.cssClass == '' || row.cssClass == null)">{{
						row.dictLabel
					}}</span>
					<el-tag
						v-else
						:type="row.listClass === 'default' ? 'primary' : row.listClass ?? 'primary'"
						:class="row.cssClass"
					>
						{{ row.dictLabel }}
					</el-tag>
				</template>
				<template #status="{ row }">
					<DictTag
						:options="sysNormalDisable"
						:value="row.status"
					/>
				</template>
				<template #createTime="{ row }">
					{{ formatDate(row.createTime) }}
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['system:dict:edit'])"
						type="primary"
						link
						@click="handleEdit(row)"
					>
						修改
					</el-button>
					<el-button
						v-if="checkPermission(['system:dict:remove'])"
						type="danger"
						link
						@click="handleDelete(row.id)"
					>
						删除
					</el-button>
				</template>
			</QTable>
		</div>
		<DataEditDialog
			ref="editDialogRef"
			:sys-normal-disable="sysNormalDisable"
			@refresh="getTableData"
		/>
	</div>
</template>
